﻿using DayuCode.Designer.Common;
using DayuCode.Designer.Entity;
using DayuCode.Designer.Entity.UI;
using DayuCode.Designer.Model;
using DayuCode.Designer.Service;
using DayuCode.Designer.Service.ui;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace DayuCode.Designer.Forms
{
    public partial class FormTableUIConfig : UIPanel
    {
        long m_funcId;
        long m_projectId;
        long m_tableId = 0;
        private PageConfigVO m_pageConfigVO;
        private string m_pageConfigJson = "";
        public FormTableUIConfig(IContainer components)
        {
            InitializeComponent();
            dgvTables.AutoGenerateColumns = false;
            dgvColumns.AutoGenerateColumns = false;

            cmbTerminalType.Items.Add(new CodeItem(TerminalType.WEB, "PC Web"));
            cmbTerminalType.Items.Add(new CodeItem(TerminalType.APP, "手机APP"));
            cmbTerminalType.Items.Add(new CodeItem(TerminalType.PAD, "平板PAD"));
            cmbTerminalType.SelectedIndex = 0;

            cmbFormColumnCount.SelectedIndex = 0;

            List<Object> colsSpanList = new List<Object>();
            colsSpanList.Add(new { ColSpan = 1, Name = "1" });
            colsSpanList.Add(new { ColSpan = 2, Name = "2" });
            d4ColSpan.ValueMember = "ColSpan";
            d4ColSpan.DisplayMember = "Name";
            d4ColSpan.DataSource = colsSpanList;            
        }

        public void SetFunc(long projectId, long funcId)
        {
            this.m_projectId = projectId;
            this.m_funcId = funcId;
            loadTables();
        }

        private void loadTables()
        {
            dgvColumns.DataSource = null;
            var tables = DataTableHandler.getDataTables(m_funcId);
            dgvTables.DataSource = tables;
            if(tables.Count > 0)
            {
                dgvTables.SelectedIndex = 0;
            }
        }

        private void btnAddTable_Click(object sender, EventArgs e)
        {
            if (m_projectId == 0) return;
            FormDataTable form = new FormDataTable(0, m_projectId, m_funcId);
            form.Owner = this.FindForm();
            if(form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                loadTables();
            }
        }

        private void btnEditTable_Click(object sender, EventArgs e)
        {
            if (m_projectId == 0) return;
            if (dgvTables.SelectedRows.Count == 0)
            {
                (this.FindForm() as UIForm).ShowInfoTip("请先选中需要修改的表");
                return;
            }
            HDataTable table = dgvTables.SelectedRows[0].DataBoundItem as HDataTable;
            FormDataTable form = new FormDataTable((long)table.Id, m_projectId, m_funcId);
            form.Owner = this.FindForm();
            if (form.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                m_tableId = 0;
                loadTables();
            }
        }

        private void btnDelTable_Click(object sender, EventArgs e)
        {
            if (m_projectId == 0) return;
            if (dgvTables.SelectedRows.Count == 0)
            {
                (this.FindForm() as UIForm).ShowInfoTip("请先选中需要移除的表");
                return;
            }
            HDataTable table = dgvTables.SelectedRows[0].DataBoundItem as HDataTable;
            if ((this.FindForm() as UIForm).ShowAskDialog("确认从功能中移除表 " + table.TableName + " 吗？"))
            {
                DataTableHandler.deleteDataTable((long)table.Id);
                loadTables();
            }
        }

        private void checkSavePageConfigVO()
        {
            if (m_pageConfigVO == null) return;
            bool shouldSave = false;
            if (string.IsNullOrEmpty(m_pageConfigJson))
            {
                shouldSave = false;
            }
            else
            {
                this.getPageConfigValueFromUI();
                string newJson = JsonConvert.SerializeObject(m_pageConfigVO);
                if (!m_pageConfigJson.Equals(newJson))
                {
                    shouldSave = true;
                    
                }
            }

            if (shouldSave && (this.FindForm()).ShowAskDialog("保存", "表字段和功能的配置项已经修改，是否保存？"))
            {
                SavePageConfig(true);
            }
        }

        private void getPageConfigVO(long tableId, string terminalType, bool checkSave)
        {
            m_tableId = tableId;
            if (checkSave)
            {
                checkSavePageConfigVO();
            }
            m_pageConfigVO = PageConfigHandler.getPageConfigVO(tableId, terminalType);
            bindValuesToUI();
        }

        private void bindValuesToUI()
        {
            m_pageConfigJson = JsonConvert.SerializeObject(m_pageConfigVO);

            d3QuerySqlOperator.DisplayMember = "Name";
            d3QuerySqlOperator.ValueMember = "Code";
            d3QuerySqlOperator.DataSource = m_pageConfigVO.QuerySqlOperators;

            d3QueryInputElementType.DisplayMember = "Name";
            d3QueryInputElementType.ValueMember = "Code";
            d3QueryInputElementType.DataSource = m_pageConfigVO.QueryElementTypes;

            d2CellTextType.DisplayMember = "Name";
            d2CellTextType.ValueMember = "Code";
            d2CellTextType.DataSource = m_pageConfigVO.CellTextTypes;

            d2InputElementType.DisplayMember = "Name";
            d2InputElementType.ValueMember = "Code";
            d2InputElementType.DataSource = m_pageConfigVO.InputElementTypes;

            d4FormElementType.DisplayMember = "Name";
            d4FormElementType.ValueMember = "Code";
            d4FormElementType.DataSource = m_pageConfigVO.FormElementTypes;

            dgvColumns.DataSource = null;
            dgvColumns.DataSource = m_pageConfigVO.ColumnVOList;

            HForm form = m_pageConfigVO.Form;
            for (int i = 0; i < cmbFormColumnCount.Items.Count; i++)
            {
                if (cmbFormColumnCount.Items[i].ToString().Equals("" + form.ColumnCount))
                {
                    cmbFormColumnCount.SelectedIndex = i;
                    break;
                }
            }

            HDataTree dataTree = m_pageConfigVO.DataTree;
            chkCatalogAsync.Checked = dataTree.CatalogAsync ?? false;
            chkCatalogEditable.Checked = dataTree.CatalogEditable ?? false;
            chkShowLeafNode.Checked = dataTree.ShowLeafNode ?? false;

            var grid = m_pageConfigVO.DataGrid;
            chkPagination.Checked = grid.Pagination ?? false;
            txtPageSize.Text = "" + grid.PageSize;
            chkLineNumberColumn.Checked = grid.LineNumberColumn ?? false;
            chkChkboxColumn.Checked = grid.ChkboxColumn ?? false;
            chkChkboxMultiChked.Checked = grid.ChkboxMultiChked ?? false;
            chkOptrCellInfoBtn.Checked = grid.OptrCellInfoBtn ?? false;
            chkOptrCellEditBtn.Checked = grid.OptrCellEditBtn ?? false;
            chkOptrCellDelBtn.Checked = grid.OptrCellDelBtn ?? false;
            chkOptrCellFileBtn.Checked = grid.OptrCellFileBtn ?? false;
            //chkOptrCellLockData.Checked = grid.OptrCellLockData ?? false;
            chkGridEditable.Checked = grid.GridEditable ?? false;
            chkGridEditSaveType.Checked = grid.GridEditSaveType ?? false;
            chkToolbarAddBtn.Checked = grid.ToolbarAddBtn ?? false;
            chkToolbarEditBtn.Checked = grid.ToolbarEditBtn ?? false;
            chkToolbarDelBtn.Checked = grid.ToolbarDelBtn ?? false;
            //chkToolbarLockData.Checked = grid.ToolbarLockData ?? false;
            chkToolbarExpBtn.Checked = grid.ToolbarExpBtn ?? false;
            chkGridColumnLine.Checked = grid.GridColumnLine ?? false;
            chkUseRecurseQuery.Checked = grid.UseRecurseQuery ?? false;
        }

        private bool getPageConfigValueFromUI()
        {
            if (m_pageConfigVO == null) return false;
            m_pageConfigVO.Form.ColumnCount = Convert.ToInt32(cmbFormColumnCount.SelectedItem.ToString());
            m_pageConfigVO.DataTree.CatalogAsync = chkCatalogAsync.Checked;
            m_pageConfigVO.DataTree.CatalogEditable = chkCatalogEditable.Checked;
            m_pageConfigVO.DataTree.ShowLeafNode = chkShowLeafNode.Checked;

            var grid = m_pageConfigVO.DataGrid;
            grid.Pagination = chkPagination.Checked;
            grid.PageSize = Cast.ToInt32(txtPageSize.Text, 10);
            grid.LineNumberColumn = chkLineNumberColumn.Checked;
            grid.ChkboxColumn = chkChkboxColumn.Checked;
            grid.ChkboxMultiChked = chkChkboxMultiChked.Checked;
            grid.OptrCellInfoBtn = chkOptrCellInfoBtn.Checked;
            grid.OptrCellEditBtn = chkOptrCellEditBtn.Checked;
            grid.OptrCellDelBtn = chkOptrCellDelBtn.Checked;
            grid.OptrCellFileBtn = chkOptrCellFileBtn.Checked;
            grid.GridEditable = chkGridEditable.Checked;
            grid.GridEditSaveType = chkGridEditSaveType.Checked;
            grid.ToolbarAddBtn = chkToolbarAddBtn.Checked;
            grid.ToolbarEditBtn = chkToolbarEditBtn.Checked;
            grid.ToolbarDelBtn = chkToolbarDelBtn.Checked;
            grid.ToolbarExpBtn = chkToolbarExpBtn.Checked;
            grid.GridColumnLine = chkGridColumnLine.Checked;
            grid.UseRecurseQuery = chkUseRecurseQuery.Checked;

            if (chkGridEditable.Checked)
            {
                int editColumnCount = m_pageConfigVO.ColumnVOList.FindAll(col => col.EditAble ?? false == true).Count;
                if(editColumnCount == 0)
                {
                    (this.FindForm() as UIForm).ShowErrorTip("设置了表格单元格可编辑，必须选择可以编辑的列，保存操作已取消", 2000);
                    return false;
                }
            }
            return true;
        }
    
        public bool SavePageConfig(bool force)
        {
            if (getPageConfigValueFromUI())
            {
                string newJson = JsonConvert.SerializeObject(m_pageConfigVO);
                if (force || !m_pageConfigJson.Equals(newJson))
                {
                    m_pageConfigVO = PageConfigHandler.savePageConfigVO(m_pageConfigVO);
                    bindValuesToUI();
                    m_pageConfigJson = JsonConvert.SerializeObject(m_pageConfigVO);
                }
                return true;
            }
            else return false;
        }

        private void dgvTables_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            HDataTable table = dgvTables.Rows[e.RowIndex].DataBoundItem as HDataTable;

            if (m_tableId == table.Id) return;

            CodeItem terminalTypeItem = cmbTerminalType.SelectedItem as CodeItem;
            getPageConfigVO(table.Id??0, terminalTypeItem.Code, true);
        }

        private void cmbTerminalType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(dgvTables.SelectedRows.Count > 0)
            {
                HDataTable table = dgvTables.SelectedRows[0].DataBoundItem as HDataTable;
                CodeItem terminalTypeItem = cmbTerminalType.SelectedItem as CodeItem;
                getPageConfigVO(table.Id ?? 0, terminalTypeItem.Code, true);
            }
        }

        private void chkShowTableProp_CheckedChanged(object sender, EventArgs e)
        {
            bool visib = chkShowTableProp.Checked;
            this.d1ColumnAliasName.Visible = visib;
            this.d1CodeType.Visible = visib;
            this.d1Unit.Visible = visib;
            this.d1AggregateGroup.Visible = visib;
            this.d1AggregateFunc.Visible = visib;
            this.d1RefColumnInfo.Visible = visib;
            this.d1DataType.Visible = visib;
            this.d1DataLength.Visible = visib;
            this.d1DataScale.Visible = visib;
            this.d1MinCharLength.Visible = visib;
            this.d1MaxCharLength.Visible = visib;
            this.d1MinValue.Visible = visib;
            this.d1MaxValue.Visible = visib;
            this.d1CharsetType.Visible = visib;
        }

        private void chkShowGridProp_CheckedChanged(object sender, EventArgs e)
        {
            bool visib = chkShowGridProp.Checked;
            
            this.d2GridColumn.Visible = visib;
            this.d2ColumnGroup.Visible = visib;
            this.d2ColumnWidth.Visible = visib;
            this.d2CellTextType.Visible = visib;
            this.d2EditMenu.Visible = visib;
            this.d2Fixed.Visible = visib;
            this.d2RenderScript.Visible = visib;
            this.d2VisibleStatus.Visible = visib;
            this.d2EditAble.Visible = visib;
            this.d2InputElementType.Visible = visib;
            this.d2MergeCell.Visible = visib;
            this.d2GridColumnOrdnum.Visible = visib;
        }

        private void chkShowQueryProp_CheckedChanged(object sender, EventArgs e)
        {
            bool visib = chkShowQueryProp.Checked;

            this.d3QueryField.Visible = visib;
            this.d3QuerySqlOperator.Visible = visib;
            this.d3QueryInputElementType.Visible = visib;
            this.d3QueryRequired.Visible = visib;
            this.d3QueryMultiValue.Visible = visib;
        }

        private void chkShowFormProp_CheckedChanged(object sender, EventArgs e)
        {
            bool visib = chkShowFormProp.Checked;
            
            this.d4FormField.Visible = visib;
            this.d4FormElementType.Visible = visib;
            this.d4Required.Visible = visib;
            this.d4InputTip.Visible = visib;
            this.d4FormColumnGroup.Visible = visib;
            this.d4ValidationRules.Visible = visib;
            this.d4ColSpan.Visible = visib;
            this.d4FormFieldOrdnum.Visible = visib;
        }

        private void chkShowGridColumns_CheckedChanged(object sender, EventArgs e)
        {
            //setColumnsFilter();
        }

        private void chkShowQueryColumns_CheckedChanged(object sender, EventArgs e)
        {
            //setColumnsFilter();
        }

        private void chkShowFormColumns_CheckedChanged(object sender, EventArgs e)
        {
            //setColumnsFilter();
        }

        //private void setColumnsFilter()
        //{
        //    if (!chkShowGridColumns.Checked && !chkShowQueryColumns.Checked && !chkShowFormColumns.Checked)
        //    {
        //        columnBindingSource.Filter = null;
        //    }
        //    else
        //    {
        //        string filter = "";
        //        if (chkShowGridColumns.Checked)
        //        {
        //            filter += " and GridColumn=true";
        //        }
        //        if (chkShowQueryColumns.Checked)
        //        {
        //            filter += " and QueryField=true";
        //        }
        //        if (chkShowFormColumns.Checked)
        //        {
        //            filter += " and FormField=true";
        //        }
        //        if(filter.StartsWith(" and ")){
        //            filter = filter.Substring(5);
        //        }
        //        columnBindingSource.Filter = filter;//filter 对Class对象不起效
        //    }
        //}

        private void dgvColumns_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;            
        }

        public string GetTerminalType()
        {
            string terminalType = (cmbTerminalType.SelectedItem as CodeItem).Code;
            return terminalType;
        }

        private void menuItemReloadColumns_Click(object sender, EventArgs e)
        {
            if (dgvTables.SelectedRows.Count == 0)
            {
                (this.FindForm() as UIForm).ShowInfoTip("请先选中表");
                return;
            }
            HDataTable table = dgvTables.SelectedRows[0].DataBoundItem as HDataTable;
            DataTableHandler.syncColumns((long)table.Id);

            CodeItem terminalTypeItem = cmbTerminalType.SelectedItem as CodeItem;
            m_tableId = 0;
            getPageConfigVO(table.Id ?? 0, terminalTypeItem.Code, true);

            (this.FindForm() as UIForm).ShowSuccessTip("完成从pdm中重新读取字段信息");
        }

        private void btnReloadPageConfigVO_Click(object sender, EventArgs e)
        {
            if (m_tableId <= 0) return;
            if((this.FindForm()).ShowAskDialog("刷新", "重新加载页面配置，会丢失当前没有保存的配置项，是否继续？"))
            {
                long tableId = m_tableId;
                m_tableId = 0;
                CodeItem terminalTypeItem = cmbTerminalType.SelectedItem as CodeItem;
                getPageConfigVO(tableId, terminalTypeItem.Code, true);
                (this.FindForm() as UIForm).ShowSuccessTip("已重新加载数据");
            }
        }
    }
}
